package org.flashbrighton.as3bots.utils
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import flash.utils.getQualifiedSuperclassName;
	
	import org.flashbrighton.as3bots.bots.BaseBot;
	
	public final class BotLoader
	{
		protected var name : String;
		protected var loader : Loader;
		protected var successCallback : Function ;
		protected var errorCallback : Function ;
		protected var context : LoaderContext;
		
		public function BotLoader( name : String , successCallback : Function , errorCallback : Function )
		{
			this.name = name;
			this.successCallback = successCallback;
			this.errorCallback = errorCallback;
			var context:LoaderContext = new LoaderContext();
	        context.applicationDomain = ApplicationDomain.currentDomain;
			context.applicationDomain = new ApplicationDomain();


		}
		
		public function load( request : URLRequest ):void
		{
			setup();
			loader.load( request );
		}
		
		public function loadBytes( bytes : ByteArray ):void
		{
			setup();
			loader.loadBytes( bytes );
		}


		protected function setup():void
		{
			loader = new Loader();
        	loader.contentLoaderInfo.addEventListener( Event.COMPLETE , handleLoadComplete );
		}
		
		protected function handleLoadComplete( e:Event ):void
		{
			var s : Sprite = Loader(e.target.loader).content as Sprite;
			var className : String = name;
			var botClass : Class;
			var botTestClass : Class;
			var b : BaseBot;
			
			try
			{
				botClass = s.loaderInfo.applicationDomain.getDefinition( className ) as Class;
				
			}
			catch( e:Error )
			{
				errorCallback( 'Could not find bot class '+className );
				return;
			}
			try
			{
				botTestClass = s.loaderInfo.applicationDomain.getDefinition( className + "Test") as Class;
			}
			catch( e:Error )
			{
				errorCallback( 'Could not find bot test class '+className + "Test !");
				return;
			}
			
			b = new botClass; 
			
			if( ! b is BaseBot )
			{
				errorCallback('Class '+className+' does not extend BaseBot, was '+getQualifiedSuperclassName( b )+' instead');
				
				return;
			}
			
			successCallback( b, botTestClass );
		}
	}
}